#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
import logging
from aggmon.consumer import Consumer
from aggmon.aggmon_component import Component


class Aggregator(Consumer):
    def __init__( self, input_channel=None, group_channels=[], upstream_channels=[], topic="#", hierarchy=None ):
        if self.__class__.__name__.startswith( "Host" ):
            self._output_channels = group_channels
        else:
            self._output_channels = upstream_channels
        self._topic = topic
        self.consumer = Consumer.__init__( self, hierarchy=hierarchy, input_channel=input_channel, topic=topic )
        logging.info( "Aggregator %s will publish to channels: %s" % (type(self).__name__,
                                                                      ", ".join( [ channel.url for channel in self._output_channels ] ) ) )

    def publish( self, topic, metric ):
        for channel in self._output_channels:
            logging.debug( "Aggregator '%s' publishing to channel %s with topic %s : %s"
                           % (type(self).__name__, channel.url, topic, repr(metric)) )
            channel.publish( topic, metric )


class AggregatorComponent(Component):
    def __init__( self, *args, **kwds ):
        Component.__init__( self, *args, **kwds )
        self.allowed_kwds = ["input_channel", "group_channels", "upstream_channels", "topic", "hierarchy"]

    def instantiate( self, *args, **kwds ):
        # lose the reference to any previous instance
        self.instance = None
        try:
            logging.debug( "instantiating: %s" % self.name )
            self.instance = Aggregator( *args, **kwds )
        except Exception, e:
            raise e

    def stop( self ):
        if self.instance.is_running():
            self.state = Component.STOPPED
            self.instance.unsubscribe()
